<?php if (session_id() == "")
		session_start();


	/*
	' Define the PayPal Redirect URLs for Express Checkout
	' 	This is the URL that the buyer is first sent to do authorize payment with their paypal account
	' 	change the URL depending if you are testing on the sandbox or the live PayPal site
	'
	' For the sandbox, the URL is https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=
	' For the live site, the URL is https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=
	*/

	

	


/*
	'-------------------------------------------------------------------------------------------------------------------------------------------
	' Purpose: 	Prepares the parameters for direct payment (credit card) and makes the call.
	'
	' Inputs:
	'		paymentType: 		paymentType has to be one of the following values: Sale or Order
	'		paymentAmount:  	Total value of the shopping cart
	'		creditCardType		Credit card type has to one of the following values: Visa or MasterCard or Discover or Amex or Switch or Solo
	'		creditCardNumber	Credit card number
	'		expDate				Credit expiration date
	'		cvv2				CVV2
	'		firstName			Customer's First Name
	'		lastName			Customer's Last Name
	'		street				Customer's Street Address
	'		city				Customer's City
	'		state				Customer's State
	'		zip					Customer's Zip
	'		countryCode			Customer's Country represented as a PayPal CountryCode
	'		currencyCode		Customer's Currency represented as a PayPal CurrencyCode
	'		orderdescription	Short textual description of the order
	'
	' Note:
	'		There are other optional inputs for credit card processing that are not presented here.
	'		For a complete list of inputs available, please see the documentation here for US and UK:
	'		http://www.paypal.com/en_US/pdf/PayflowPro_Guide.pdf
	'		https://www.paypal.com/en_GB/pdf/PP_WebsitePaymentsPro_IntegrationGuide.pdf
	'
	' Returns:
	'		The NVP Collection object of the Response.
	'--------------------------------------------------------------------------------------------------------------------------------------------
	*/
	function DirectPayment( $invnum, $paymentType, $paymentAmount, $tax, $shipping, $creditCardType, $creditCardNumber, $expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip, $email, $phone, $countryCode, $currencyCode, $orderdescription, $shipping_address, $shipping_city, $shipping_state, $shipping_zip )
	{
		// Construct the parameter string that describes the credit card payment
		$replaceme = array("-", " ");
		$card_num = str_replace($replaceme,"",$creditCardNumber);

		$nvpstr = "&TENDER=C";
		if ("Sale" == $paymentType)
		{
			$nvpstr .= "&TRXTYPE=S";
		}
		elseif ("Authorization" == $paymentType)
		{
			$nvpstr .= "&TRXTYPE=A";
		}
		else //default to sale
		{
			$nvpstr .= "&TRXTYPE=S";
		}

		// Other information
		$ipaddr = $_SERVER['REMOTE_ADDR'];

		$nvpstr .= '&INVNUM='.$invnum.'&ACCT='.$card_num.'&CVV2='.$cvv2.'&EXPDATE='.$expDate.'&ACCTTYPE='.$creditCardType.'&AMT='.$paymentAmount.'&CURRENCY='.$currencyCode.'&TAXAMT='.$tax.'&FREIGHTAMT='.$shipping;
		$nvpstr .= '&FIRSTNAME='.$firstName.'&LASTNAME='.$lastName.'&STREET='.$street.'&CITY='.$city.'&STATE='.$state.'&ZIP='.$zip.'&EMAIL='.$email.'&PHONEUM='.$phone.'&COUNTRY='.$countryCode;
                $nvpstr .= '&SHIPTOSTREET='.$shipping_address.'&SHIPTOCITY='.$shipping_city.'&SHIPTOSTATE='.$shipping_state.'&SHIPTOCOUNTRY=US&SHIPTOZIP='.$shipping_zip;
		$nvpstr .= '&CLIENTIP='. $ipaddr . '&ORDERDESC=' . $orderdescription;
		// Transaction results (especially values for declines and error conditions) returned by each PayPal-supported
		// processor vary in detail level and in format. The Payflow Verbosity parameter enables you to control the kind
		// and level of information you want returned.
		// By default, Verbosity is set to LOW. A LOW setting causes PayPal to normalize the transaction result values.
		// Normalizing the values limits them to a standardized set of values and simplifies the process of integrating
		// the Payflow SDK.
		// By setting Verbosity to MEDIUM, you can view the processor's raw response values. This setting is more “verbose”
		// than the LOW setting in that it returns more detailed, processor-specific information.
		// Review the chapter in the Developer's Guides regarding VERBOSITY and the INQUIRY function for more details.
		// Set the transaction verbosity to MEDIUM.
		$nvpstr .= '&VERBOSITY=MEDIUM';

		// The $unique_id field is storing our unique id that we'll use in the request id header.
		$unique_id = date('ymd-H').rand(1000,9999);

		/*'-------------------------------------------------------------------------------------------
		' Make the call to Payflow to finalize payment
		' If an error occured, show the resulting errors
		'-------------------------------------------------------------------------------------------
		*/
		$resArray = hash_call($nvpstr,$unique_id);

		return $resArray;
	}

	/**
	  '-------------------------------------------------------------------------------------------------------------------------------------------
	  * hash_call: Function to perform the API call to Payflow
	  * @nvpStr is nvp string.
	  * returns an associtive array containing the response from the server.
	  '-------------------------------------------------------------------------------------------------------------------------------------------
	*/
	function hash_call($nvpStr,$unique_id)
	{
            /********************************************
	Payflow API Module

	Defines all the global variables and the wrapper functions
	********************************************/
	$PROXY_HOST = '127.0.0.1';
	$PROXY_PORT = '808';

	$Env = "live";

	//'------------------------------------
	//' Payflow API Credentials
	//'------------------------------------
	$API_User="docuimage";
	//' Fill in the API_Password variable yourself, the wizard will not do this automatically
	$API_Password="technology01";
	$API_Vendor="docuimage";
	$API_Partner="PayPal";

	// BN Code
	$sBNCode = "PF-CCWizard";

        if ($Env == "pilot")
	{
		$API_Endpoint = "https://pilot-payflowpro.paypal.com";
		$PAYPAL_URL = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
	}
	else
	{
		$API_Endpoint = "https://payflowpro.paypal.com";
		$PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
	}

	$USE_PROXY = false;
		//declaring of global variables
		/*global $API_Endpoint, $API_User, $API_Password, $API_Vendor, $API_Partner;
		global $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
		global $gv_ApiErrorURL;
		global $sBNCode;*/

		$len = strlen($nvpStr);
		$headers[] = "Content-Type: text/namevalue";
		$headers[] = "Content-Length: " . $len;
		// Set the server timeout value to 45, but notice below in the cURL section, the timeout
		// for cURL is set to 90 seconds.  Make sure the server timeout is less than the connection.
		$headers[] = "X-VPS-CLIENT-TIMEOUT: 45";
		$headers[] = "X-VPS-REQUEST-ID:" . $unique_id;

		// set the host header
		if ($Env == "pilot")
		{
			$headers[] = "Host: pilot-payflowpro.paypal.com";
		}
		else
		{
			$headers[] = "Host: payflowpro.paypal.com";
		}

		//setting the curl parameters.
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_VERBOSE, 1);

		//turning off the server and peer verification(TrustManager Concept).
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 90); 		// times out after 90 secs
		curl_setopt($ch, CURLOPT_POST, 1);

	    //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
	    //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php
		if($USE_PROXY)
			curl_setopt ($ch, CURLOPT_PROXY, $PROXY_HOST. ":" . $PROXY_PORT);

		//NVPRequest for submitting to server
		$nvpreq = "USER=".$API_User.'&VENDOR='.$API_Vendor.'&PARTNER='.$API_Partner.'&PWD='.$API_Password . $nvpStr . "&BUTTONSOURCE=" . urlencode($sBNCode);

		//setting the nvpreq as POST FIELD to curl
		curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

		//getting response from server
		$response = curl_exec($ch);

		//convrting NVPResponse to an Associative Array
		$nvpResArray=deformatNVP($response);
		$nvpReqArray=deformatNVP($nvpreq);
		$_SESSION['nvpReqArray']=$nvpReqArray;

		if (curl_errno($ch))
		{
			// moving to display page to display curl errors
			  $_SESSION['curl_error_no']=curl_errno($ch) ;
			  $_SESSION['curl_error_msg']=curl_error($ch);

			  //Execute the Error handling module to display errors.
		}
		else
		{
			 //closing the curl
		  	curl_close($ch);
		}

		return $nvpResArray;
	}



/** This function will take NVPString and convert it to an Associative Array and it will decode the response.
  * It is usefull to search for a particular key and displaying arrays.
  * @nvpstr is NVPString.
  * @nvpArray is Associative Array.
  */

function deformatNVP($nvpstr)
{

	$intial=0;
 	$nvpArray = array();


	while(strlen($nvpstr)){
		//postion of Key
		$keypos= strpos($nvpstr,'=');
		//position of value
		$valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);

		/*getting the Key and Value values and storing in a Associative Array*/
		$keyval=substr($nvpstr,$intial,$keypos);
		$valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
		//decoding the respose
		$nvpArray[urldecode($keyval)] =urldecode( $valval);
		$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
     }
	return $nvpArray;
}



//$paymentType=urlencode($_POST['paymentType']);


/*
$nvpstr="&TRXTYPE=S&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber&EXPDATE=".
$padDateMonth.$expDateYear."&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName&STREET=$address1
&CITY=$city&STATE=$state"."&ZIP=$zip&COUNTRYCODE=US&CURRENCYCODE=$currencyCode&SHIPTOSTREET=$shipping_address
&SHIPTOCITY=$shipping_city&SHIPTOSTATE=$shipping_state&SHIPTOCOUNTRY=US&SHIPTOZIP=$shipping_zip";*/
/*
TRXTYPE=S&TENDER=C&USER=SuperMerchant&PWD=SuperUserPassword&PARTNER=PayPal&
ACCT=5105105105105100&EXPDATE=1209&AMT=99.06&COMMENT1=Reservation&FIRSTNAME
=John&LASTNAME=Jones&STREET=123 Main St.&CITY=San
Jose&STATE=CA&ZIP=123451234&BILLTOCOUNTRY=US&CVV2=123&CUSTIP=0.0.0.0
*/


/* Make the API call to PayPal, using API signature.
   The API response is stored in an associative array called $resArray */
/*$resArray = hash_call("doDirectPayment",$nvpstr);
echo '<br>'.$nvpstr;
echo '<br>'.implode(',',$resArray);*/
/* Display the API response back to the browser.
   If the response from PayPal was a success, display the response parameters'
   If the response was an error, display the errors received using APIError.php.
   */
/*$ack = strtoupper($resArray["ACK"]);

if($ack!="SUCCESS")  {
    $_SESSION['reshash']=$resArray;
	$location = url_for('invoices/apiError');
		 header("Location: $location");
   }
*/
if ( $creditCardType == "Visa" || $creditCardType == "MasterCard" || $creditCardType == "Amex" || $creditCardType == "Discover" )
{
	/*
	'------------------------------------
	' The paymentAmount is the total value of
	' the shopping cart, that was set
	' earlier in a session variable
	' by the shopping cart page
	'------------------------------------
	*/

	$finalPaymentAmount =  $amount;

	$expDate 				= $padDateMonth.$expDateYear; // ' Set this to the credit card expiry date entered on the Billing page
	$countryCode 			= "US"; // ' Set this to the PayPal code for the Country of the customer's address that was entered on the Billing page
	$orderDescription 	= "Testing Order"; // ' Set this to the textual description of this order

	$paymentType			= "Sale";

	/*
	'------------------------------------
	'
	' The DirectPayment function is defined in the file PayPalFunctions.php,
	' that is included at the top of this file.
	'-------------------------------------------------
	*/

	$resArray = DirectPayment ( $invnum, $paymentType, $finalPaymentAmount, $tax, $shipping, $creditCardType,
                $creditCardNumber, $expDate, $cvv2, $firstName, $lastName, $street,
                $city, $state, $zip, $email, $phone, $countryCode, $currencyCode, $orderDescription,
                $shipping_address, $shipping_city, $shipping_state, $shipping_zip );
	$ack = $resArray["RESULT"];
	if( $ack != "0" )
	{
		// See pages 50 through 65 in https://cms.paypal.com/cms_content/US/en_US/files/developer/PP_PayflowPro_Guide.pdf for a list of RESULT values (error codes)
		//Display a user friendly Error on the page using any of the following error information returned by Payflow
		$ErrorCode = $ack;
		$ErrorMsg = $resArray["RESPMSG"];

		echo "Credit Card transaction failed. ";
		echo "Error Message: " . $ErrorMsg;
		echo "Error Code: " . $ErrorCode;
	}
}
?>

<div id="content-wrapper-faq" class="corner">
<span class="titulo_seccion-faq">DoDirect<span class="color">Paymentd</span></span><br />
<br />


	<b>Thank you for your payment!</b><br><br>

   <table width=400>

        <?php $invoice = Doctrine_Core::getTable('Invoice')->find($invnum);
   		 	
   		 ?>
       <table class="api" width=400>
	        	<?php
    		foreach($resArray as $key => $value) :
                    if ($key == 'PNREF') $invoice->setIdTransaction($value);
                    if ($key == 'AUTHCODE') $invoice->setAuthCode($value);
                    if ($key == 'RESULT') $invoice->setResult($value);
                    if ($key == 'RESPMSG') $invoice->setMessage($value);
                    if ($key == 'RESULT') :
                      if ($value==0) :
                        $invoice->setIsPaid(1);
                      else :
                        $invoice->setIsPaid(0);
                      endif;
                    endif;

                    echo "<tr><td> $key:</td><td>$value</td>";
                endforeach;

                if ($invoice->getIsPaid() == "0") :
                   $invoice->save();
                   $invoice->sendEmail($invoice->getIsPaid(),$invoice->User->getEmail());
                   sfContext::getInstance()->getController()->redirect('invoices/error?id_invoice='.$invoice->getIdInvoice());
                else :
                   $invoice->setPaymentDate(date('Y-m-d'));
                   $invoice->save();
                   $invoice->sendEmail($invoice->getIsPaid(),$invoice->User->getEmail());
                   sfContext::getInstance()->getController()->redirect('invoices/show?id_invoice='.$invoice->getIdInvoice());
                endif;
                
       			?>
        </table>
    </table>
</div>